use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::RwLock;
use crate::remote::RemoteError;

/// Message serializer trait
pub trait MessageSerializer: Send + Sync {
    /// Serialize a message
    fn serialize(&self, message: Box<dyn Any + Send + Sync>) -> Result<Vec<u8>, RemoteError>;
    
    /// Deserialize a message
    fn deserialize(&self, bytes: &[u8]) -> Result<Box<dyn Any + Send + Sync>, RemoteError>;
    
    /// Get this object as Any for downcasting
    fn as_any(&self) -> &dyn Any;
}

/// Serializer registry
pub struct SerializerRegistry {
    /// Map of serializer IDs to serializers
    serializers: RwLock<HashMap<u32, Arc<dyn MessageSerializer>>>,
    /// Map of type names to type IDs
    type_names: RwLock<HashMap<String, u32>>,
}

impl SerializerRegistry {
    /// Create a new serializer registry
    pub fn new() -> Self {
        Self {
            serializers: RwLock::new(HashMap::new()),
            type_names: RwLock::new(HashMap::new()),
        }
    }
    
    /// Register a serializer
    pub fn register(&self, id: u32, serializer: Arc<dyn MessageSerializer>) {
        self.serializers.write().insert(id, serializer);
    }
    
    /// Get a serializer by ID
    pub fn get(&self, id: u32) -> Option<Arc<dyn MessageSerializer>> {
        self.serializers.read().get(&id).cloned()
    }
    
    /// Register a serializer with auto-generated ID
    pub fn register_serializer(&self, serializer: Arc<dyn MessageSerializer>) {
        let id = self.serializers.read().len() as u32;
        self.register(id, serializer);
    }
    
    /// Register a type name for a specific type ID
    pub fn register_type_name<T: 'static>(&self, name: &str) {
        let type_id = std::any::TypeId::of::<T>();
        let id = format!("{:?}", type_id).as_bytes().iter().fold(0u32, |acc, &b| acc.wrapping_add(b as u32));
        self.type_names.write().insert(name.to_string(), id);
    }
    
    /// Serialize a message using the appropriate serializer
    pub fn serialize<T: Any + Send + prost::Message>(&self, message: &T, serializer_id: u32) -> Result<Vec<u8>, RemoteError> {
        // Find a serializer for this type
        if let Some(serializer) = self.get(serializer_id) {
            // Try to use the serializer
            if let Some(typed_serializer) = serializer.as_any().downcast_ref::<ProtoSerializer>() {
                // 使用正确的序列化方法
                return typed_serializer.serialize_proto(message);
            }
        }
        
        Err(RemoteError::SerializationError("No suitable serializer found".to_string()))
    }
    
    /// Deserialize a message using the appropriate serializer
    pub fn deserialize<T: Any + Send + prost::Message + Default>(&self, bytes: &[u8], serializer_id: u32) -> Result<T, RemoteError> {
        // Find a serializer for this type
        if let Some(serializer) = self.get(serializer_id) {
            // Try to use the serializer
            if let Some(typed_serializer) = serializer.as_any().downcast_ref::<ProtoSerializer>() {
                // 使用正确的反序列化方法
                return typed_serializer.deserialize_proto(bytes);
            }
        }
        
        Err(RemoteError::DeserializationError("No suitable serializer found".to_string()))
    }
}

/// Protocol buffers serializer
pub struct ProtoSerializer;

impl ProtoSerializer {
    /// Create a new protocol buffers serializer
    pub fn new() -> Self {
        Self
    }
    
    /// Serialize a protobuf message
    pub fn serialize_proto<T: prost::Message>(&self, message: &T) -> Result<Vec<u8>, RemoteError> {
        let mut buf = Vec::new();
        message.encode(&mut buf)
            .map_err(|e| RemoteError::SerializationError(e.to_string()))?;
        Ok(buf)
    }
    
    /// Deserialize a protobuf message
    pub fn deserialize_proto<T: prost::Message + Default>(&self, bytes: &[u8]) -> Result<T, RemoteError> {
        T::decode(bytes)
            .map_err(|e| RemoteError::DeserializationError(e.to_string()))
    }
}

impl MessageSerializer for ProtoSerializer {
    fn serialize(&self, message: Box<dyn Any + Send + Sync>) -> Result<Vec<u8>, RemoteError> {
        // 由于无法直接在trait对象上调用encode方法，我们需要使用一个不同的方法
        // 这里我们返回一个错误，表明需要使用具体类型而不是trait对象
        Err(RemoteError::SerializationError(
            "Direct serialization of trait objects is not supported. Use a concrete type serializer instead.".to_string()
        ))
    }
    
    fn deserialize(&self, bytes: &[u8]) -> Result<Box<dyn Any + Send + Sync>, RemoteError> {
        // This is a placeholder implementation
        // In a real implementation, we'd need to know the target type
        Err(RemoteError::DeserializationError("Not implemented".to_string()))
    }
    
    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Default for SerializerRegistry {
    fn default() -> Self {
        Self::new()
    }
} 